﻿Imports System
Imports System.Web

''' <summary>
''' Methods to read and write http cookies.
''' </summary>
Public Class CookieUtil

#Region "Private constructor"

	Private Sub New()
		' Can't create instance!
	End Sub

#End Region

#Region "Get"

	''' <summary>
	''' Gets the cookie value and return as String.
	''' </summary>
	''' <returns>Cookie as String.</returns>
	Public Shared Function GetCookie(ByVal name As String, ByVal defaultValue As String) As String

		Dim c As String = GetCookie(name)

		If String.IsNullOrEmpty(c) Then
			Return defaultValue
		End If

		Return c

	End Function

	''' <summary>
	''' Gets the cookie value and return as DateTime.
	''' </summary>
	''' <returns>Cookie as DateTime.</returns>
	Public Shared Function GetCookie(ByVal name As String, ByVal defaultValue As DateTime) As DateTime

		Dim c As String = GetCookie(name)

		If String.IsNullOrEmpty(c) Then
			Return defaultValue
		End If

		Return Convert.ToDateTime(c)

	End Function

	''' <summary>
	''' Gets the cookie value and return as Int32.
	''' </summary>
	''' <returns>Cookie as Int32.</returns>
	Public Shared Function GetCookie(ByVal name As String, ByVal defaultValue As Int32) As Int32

		Dim c As String = GetCookie(name)

		If String.IsNullOrEmpty(c) Then
			Return defaultValue
		End If

		Return Convert.ToInt32(c)

	End Function

	''' <summary>
	''' Gets the cookie value and return as String.
	''' </summary>
	''' <returns>Cookie as String.</returns>
	Public Shared Function GetCookie(ByVal name As String) As String

		Dim c As HttpCookie = HttpContext.Current.Request.Cookies(name)

		If c Is Nothing Then
			Return String.Empty
		End If

		Return c.Value

	End Function

#End Region

#Region "Set"

	''' <summary>
	''' Saves the specified value to a cookie.
	''' </summary>
	Public Shared Sub SetCookie(ByVal name As String, ByVal value As String)

		SetCookie(name, value, DateTime.Now.AddDays(1))

	End Sub

	''' <summary>
	''' Saves the specified value to a cookie and sets the expiry date.
	''' </summary>
	Public Shared Sub SetCookie(ByVal name As String, ByVal value As String, ByVal expires As DateTime)

		Dim c As New HttpCookie(name, value)

		c.Expires = expires

		HttpContext.Current.Response.Cookies.Add(c)

	End Sub

	''' <summary>
	''' Saves the specified DateTime to a cookie and sets the expiry date.
	''' </summary>
	Public Shared Sub SetCookie(ByVal name As String, ByVal value As DateTime, ByVal expires As DateTime)

		SetCookie(name, value.ToString("yyyy-MM-dd HH:mm:ss"), expires)

	End Sub
	
#End Region

End Class
